﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using PhoneAppSTS.Utils;
using System.Diagnostics;
using STS.Model;
using System.Device.Location;
using System.Threading;
using Microsoft.Phone.Tasks;
using AugmentedReality;

namespace PhoneAppSTS
{
    public partial class Information : PhoneApplicationPage
    {
        private InformationUtils informationUtils;
        private GeoCoordinateWatcher watcher;
        private GeoCoordinate currentLocation;
        public Information()
        {
            InitializeComponent();
            informationUtils = new InformationUtils();
            this.DataContext = informationUtils;
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            DanePacjentow dp = ModelInstance.DanePacjentowViewModel.GetDanePacjentow();
            if (dp == null)
            {
                informationUtils.DownloadDanePacjenta(102);
            }
            else
            {
                informationUtils.TakeInformation();
            }

            Debug.WriteLine("watcher = " + (watcher == null ? "NULL" : "NOT NULL"));

            if (watcher == null)
            {
                watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
                watcher.MovementThreshold = 20.0f;
                watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(Watcher_statusChanged);
                watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(Watcher_PositionChanged);
                new Thread(CheckLocationInBackground).Start();
            }

        }

        private void CheckLocationInBackground()
        {
            watcher.TryStart(true, TimeSpan.FromSeconds(60));
        }

        private void Watcher_statusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    // The Location Service is disabled or unsupported.
                    // Check to see if the user has disabled the location service.
                    if (watcher.Permission == GeoPositionPermission.Denied)
                    {
                        // the user has disabled LocServ on their device.
                        Debug.WriteLine("You have disabled Location Service.");
                    }
                    else
                    {
                        Debug.WriteLine("Location Service is not functioning on this device.");
                    }
                    break;

                case GeoPositionStatus.Initializing:
                    // The location service is initializing.
                    Debug.WriteLine("Location Service is retrieving data...");
                    break;

                case GeoPositionStatus.NoData:
                    // The Location Service is working, but it cannot get location data
                    // due to poor signal fidelity (most likely)
                    Debug.WriteLine("Location data is not available.");
                    break;

                case GeoPositionStatus.Ready:
                    // The location service is working and is receiving location data.
                    Debug.WriteLine("Location data is available.");
                    break;
            }
        }

        private void Watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            currentLocation = new GeoCoordinate(Math.Round(e.Position.Location.Latitude, 6), Math.Round(e.Position.Location.Longitude, 6));
        }

        private void ButtonZobaczTrase_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string url = "http://bing.com/maps/default.aspx?v=2&rtp="
+ "pos." + currentLocation.Latitude.ToString().Replace(',', '.') + "_"
+ currentLocation.Longitude.ToString().Replace(',', '.') + "_" + "START"
+ "~pos." + informationUtils.Osrodek.X.ToString().Replace(',', '.')
+ "_" + informationUtils.Osrodek.Y.ToString().Replace(',', '.')
+ "_"
                    //+ Uri.EscapeUriString(this._Pois[this._LastFoundIndex].Title) // problem z wyswietlaniem etykiet
+ "KONIEC";
//+ "/5872/style=auto&lat="
//+ currentLocation.Latitude.ToString().Replace(',', '.')
//+ "&lon=" + currentLocation.Longitude.ToString().Replace(',', '.')
//+ "&z=16";
                Debug.WriteLine(url);
                WebBrowserTask webbrowser = new WebBrowserTask();
                webbrowser.Uri = new Uri(url, UriKind.Absolute);
                webbrowser.Show(); // przejście do mapy w Bing z wyznaczoną trasą  
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

        }

        private void ButtonAR_Click(object sender, RoutedEventArgs e)
        {
            if (ModelInstance.PoiViewModel.PoiItems == null)
            {
                Poi poi = new Poi();
                poi.Content = informationUtils.Osrodek.Miasto + " " + informationUtils.Osrodek.Ulica + " " + informationUtils.Osrodek.Nr;
                poi.Name = informationUtils.Osrodek.Nazwa;
                poi.Image = "/Images/informacje.png";
                poi.PoiId = 1;
                poi.Lat = informationUtils.Osrodek.X;
                poi.Lng = informationUtils.Osrodek.Y;
                ModelInstance.PoiViewModel.PoiItems = new System.Collections.ObjectModel.ObservableCollection<Poi>();
                ModelInstance.PoiViewModel.PoiItems.Add(poi);
            }

            AR.Start(null, "pl", ModelInstance.PoiViewModel.PoiItems);
        }
    }
}